package service

import (
	"context"
	"strconv"
	__ "user_service/basic/proto"
	"user_service/model"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {

	var u model.User
	u.GetUserBy(in.Mobile)

	if u.Id != 0 {
		return &__.RegisterResp{
			Code: 10000,
			Msg:  "用户已存在",
		}, nil
	}

	u = model.User{
		Username: in.Mobile,
		Password: in.Password,
	}

	u.Create()

	return &__.RegisterResp{
		Code: 200,
		Msg:  "注册成功",
	}, nil
}

func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var u model.User
	u.GetUserBy(in.Mobile)

	if u.Id == 0 {
		return &__.LoginResp{
			Code: 10000,
			Msg:  "用户不存在",
		}, nil
	}

	if u.Password != in.Password {
		return &__.LoginResp{
			Code: 10000,
			Msg:  "密码错误",
		}, nil
	}

	return &__.LoginResp{
		Code: 200,
		Msg:  "登录成功",
	}, nil
}

func (s *Server) AddVote(_ context.Context, in *__.AddVoteReq) (*__.AddVoteResp, error) {
	var v model.Vote

	v = model.Vote{
		RemainingTickets: uint(in.RemainingTickets),
		VoteType:         uint(in.VoteType),
		VoteStatus:       uint(in.VoteStatus),
		TrainNumber:      in.TrainNumber,
		Seat:             in.Seat,
		Price:            float64(in.Price),
		SeatType:         uint(in.SeatType),
	}

	v.Created()

	return &__.AddVoteResp{
		Code: 200,
		Msg:  "购买成功",
	}, nil

}

func (s *Server) ListVote(_ context.Context, in *__.LookVoteReq) (*__.LookVoteResp, error) {
	var v model.Vote
	list, err := v.List(strconv.FormatInt(in.VoteStatus, 10))
	if err != nil {
		return nil, err
	}

	var vote []*__.ListVote

	for _, m := range list {
		lis := &__.ListVote{
			RemainingTickets: int64(m.RemainingTickets),
			VoteStatus:       int64(m.VoteStatus),
		}

		vote = append(vote, lis)
	}

	return &__.LookVoteResp{
		List: vote,
	}, nil
}

func (s *Server) InfoVote(_ context.Context, in *__.InfoVoteReq) (*__.InfoVoteResp, error) {
	var v model.Vote
	v.Info(uint(in.Id))

	return &__.InfoVoteResp{
		RemainingTickets: int64(v.RemainingTickets),
		VoteType:         int64(v.VoteType),
		VoteStatus:       int64(v.VoteStatus),
		TrainNumber:      v.TrainNumber,
		Seat:             v.Seat,
		Price:            float32(v.Price),
		SeatType:         int64(v.SeatType),
		Id:               int64(v.Id),
	}, nil
}

func (s *Server) Info(_ context.Context, in *__.InfoReq) (*__.InfoResp, error) {
	var v model.Vote
	v.Info2(strconv.FormatInt(in.VoteType, 10))

	return &__.InfoResp{
		RemainingTickets: int64(v.RemainingTickets),
		VoteType:         int64(v.VoteType),
		VoteStatus:       int64(v.VoteStatus),
		TrainNumber:      v.TrainNumber,
		Seat:             v.Seat,
		Price:            float32(v.Price),
		SeatType:         int64(v.SeatType),
		Id:               int64(v.Id),
	}, nil
}
